/**
 * 首页跳转
 */
package com.itcaicai.controller;

import com.github.abel533.easyxls.EasyXls;
import com.itcaicai.model.Clinic_appoints;
import java.util.List;

import com.itcaicai.model.MovieInfo;
import com.itcaicai.model.Test;
import com.jfinal.core.Controller;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * @author icer
 *
 */
public class IndexController extends Controller {

    /**
     * 首页跳转
     */
    public void index() {
        System.out.println("index start...");
        render("/jsp/index.jsp");
        System.out.println("index end...");
    }

    /**
     * 跳往管理页
     */
    public void toMgr() {
        renderJsp("/admin/index.jsp");
    }

    /**
     * 查询处理
     */
    public void toQuery() {
        System.out.println("query start...");
        String sqlStr_id = "select *from itcc_movie_info where movieid  = ? ";
        String sqlStr_name = "select *from itcc_movie_info where name ";
        String sqlStr_actor = "select *from itcc_movie_info where actor ";
        String sqlStr_desc = "select *from itcc_movie_info where description ";
        String param = this.getPara("queryCondition");
        if (null == param) {
            param = this.getSessionAttr("condition");
        }
        System.out.println(param);
        String param_not_id = "like '%" + param + "%'";
        List<MovieInfo> movies = MovieInfo.movieDao.find(sqlStr_id, param);
        if (null == movies || movies.isEmpty()) {
            movies = MovieInfo.movieDao.find(sqlStr_name + param_not_id);
        }
        if (null == movies || movies.isEmpty()) {
            movies = MovieInfo.movieDao.find(sqlStr_actor + param_not_id);
        }
        if (null == movies || movies.isEmpty()) {
            movies = MovieInfo.movieDao.find(sqlStr_desc + param_not_id);
        }
        this.setAttr("movieInfo", movies);
        this.setSessionAttr("condition", param);
        //System.out.println(this.getSessionAttr("condition"));
        render("/jsp/searchResult.jsp");
        System.out.println("query end...");
    }

    public void toQueryOra() {
        System.out.println("query start...");
        String sqlStr_id = "select * from clinic_appoints where card_no =  ? ";
        String sqlStr_name = "select *from clinic_appoints where name ";
        String param = this.getPara("queryConditionOra");
        if (null == param) {
            param = this.getSessionAttr("conditionOra");
        }
        System.out.println(param);
        String param_not_id = "like '%" + param + "%'";
        List<Clinic_appoints> appoints = Clinic_appoints.appointsDao.find(sqlStr_id, param);

        if (null == appoints || appoints.isEmpty()) {
            appoints = Clinic_appoints.appointsDao.find(sqlStr_name + param_not_id);
        }
        this.setAttr("movieInfoOra", appoints);
        this.setSessionAttr("conditionOra", param);
        //System.out.println(this.getSessionAttr("condition"));
        render("/jsp/searchResultOra.jsp");
        System.out.println("query end...");
    }

    public void toAdd() {
        renderJsp("/jsp/add.jsp");
    }

    /**
     * 添加处理
     */
    public void toAddSubmit() {
        String movieid = this.getPara("movieid");
        String name = this.getPara("name");
        String description = this.getPara("description");
        String actor = this.getPara("actor");
        String path = this.getPara("path");
        boolean flag = new MovieInfo().set("movieid", movieid)
                .set("name", name).set("description", description)
                .set("actor", actor).set("path", path).save();
        this.setAttr("flag", flag);
        if (flag) {
            this.setSessionAttr("condition", movieid);
            toQuery();
        }
    }

    public void toAddSubmitOra() {
        boolean flag = false;
        boolean Orafailedflag = false;
        int OrafailedNum = 0;
        int ListNum = 0;
        String movieid = this.getPara("movieid");
        String name = this.getPara("name");
        String description = this.getPara("description");
        String actor = this.getPara("actor");
        String path = this.getPara("path");

        InputStream is = IndexController.class.getResourceAsStream("2.xls");
        try {
            String xmlPath = IndexController.class.getResource("/ChargesMap.xml").getPath();

            List list = EasyXls.xls2List(xmlPath, is);
            Map<String, Integer> DoctorMap = new HashMap<>();
            Collections.sort(list, new PriceComparator()); // 根据价格排序
            List ListTemp = (List) deepClone(list);
            int DoctorCount = 0;
            ListNum = list.size();
            for (int i = 0; i < ListTemp.size(); i++) {

                for (int j = 0; j < ListTemp.size(); j++) {
                    if (((String) ((Map) ListTemp.get(i)).get("CLINIC_LABEL")).
                            equals(((String) ((Map) ListTemp.get(j)).get("CLINIC_LABEL")))) {
                        //ListTemp.remove(i);
                        DoctorCount++;
                    }
                }
                DoctorMap.put((String) ((Map) list.get(i)).get("CLINIC_LABEL"), DoctorCount);
                 DoctorCount=1;
            }

            /* Map map = new HashMap();
             map.put("Name","王志强");
             map.put("Age", "9999");
             list.add(map);*/
            Date ab = new Date();
            java.sql.Date sqlDate = java.sql.Date.valueOf("2005-12-12");

            /*    flag = new Test().set("VISIT_DATE_APPTED", getTimestamp((Date)m.get("VISIT_DATE_APPTED"))).
             set("CLINIC_LABEL", m.get("CLINIC_LABEL")).
             set("VISIT_TIME_APPTED", m.get("VISIT_TIME_APPTED")).
             set("SERIAL_NO", 12).save();
             flag = new Test().set("VISIT_DATE_APPTED", getTimestamp(ab)).
             set("CLINIC_LABEL", "朱瑛").
             set("VISIT_TIME_APPTED", "上午").
             set("SERIAL_NO",11).
             save();*/
            BigDecimal aDouble = new BigDecimal(15);
            /*        flag = new Clinic_appoints().set("VISIT_DATE_APPTED", getTimestamp(ab)).
             set("CLINIC_LABEL", "朱瑛").
             set("VISIT_TIME_APPTED", "上午").
             set("SERIAL_NO",11).save();*/

            //String a = ((String) ((Map) list.get(1)).get("NAME"));
            EasyXls.list2Xls(list, xmlPath, "E:/", "testMap1.xls");

            for (int i = 0; i < ListNum; i++) {
                Map m = (Map) list.get(i);
                if (iteratorMap(m)) {
                    i--;//按顺序排完顺序后重新插入
                    OrafailedNum++;
                    String CuurDoctor = (String) m.get("CLINIC_LABEL");
                    int CuurSerial = (Integer) m.get("SERIAL_NO");
                    for (int j = 0; (j < ListNum); j++) {
                        if (((String) ((Map) list.get(j)).get("CLINIC_LABEL")).equals(CuurDoctor)) {
                            CuurSerial++;
                            ((Map) list.get(j)).put("SERIAL_NO", CuurSerial);
                            System.out.print("---------" + CuurDoctor + CuurSerial + ((String) ((Map) list.get(j)).get("NAME")) + "-----------");
                        }
                        /*Iterator ModfiyI = m.entrySet().iterator();
                         while (ModfiyI.hasNext()) {//只遍历一次,速度快
                         Map.Entry e = (Map.Entry) ModfiyI.next();
                         System.out.println(e.getKey() + "=" + e.getValue());*/

                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        flag = true;
        this.setAttr("flag", flag);
        if (flag) {
            this.setSessionAttr("condition", movieid);
            toQuery();
        }
    }

    public boolean iteratorMap(Map m) {
        boolean flag = false;
        try {
            new Clinic_appoints().
                    set("VISIT_DATE_APPTED", getTimestamp((Date) m.get("VISIT_DATE_APPTED"))).
                    set("CLINIC_LABEL", m.get("CLINIC_LABEL")).
                    set("VISIT_TIME_APPTED", m.get("VISIT_TIME_APPTED")).
                    set("SERIAL_NO", (Integer) m.get("SERIAL_NO")).
                    set("PATIENT_ID", m.get("PATIENT_ID")).
                    set("APPT_MADE_DATE", getTimestamp((Date) m.get("APPT_MADE_DATE"))).
                    set("MODE_CODE", m.get("MODE_CODE")).
                    set("CARD_NAME", m.get("CARD_NAME")).
                    set("CARD_NO", m.get("CARD_NO")).
                    set("NAME", m.get("NAME")).
                    set("SEX", m.get("SEX")).
                    set("AGE", (Integer) m.get("AGE")).
                    set("IDENTITY", m.get("IDENTITY")).
                    set("CHARGE_TYPE", m.get("CHARGE_TYPE")).
                    set("INSURANCE_NO", m.get("INSURANCE_NO")).
                    set("INSURANCE_TYPE", m.get("INSURANCE_TYPE")).
                    set("UNIT_IN_CONTRACT", m.get("UNIT_IN_CONTRACT")).
                    set("NAME_PHONETIC", m.get("NAME_PHONETIC")).
                    set("ID_NO", m.get("ID_NO")).
                    set("START_TIME", getTimestamp((Date) m.get("START_TIME"))).
                    set("END_TIME", getTimestamp((Date) m.get("END_TIME"))).
                    set("TELEPHONE", m.get("TELEPHONE"))
                    // set("FIRSTFLAG", m.get("FIRSTFLAG")).
                    // set("NEXT_OF_KIN", m.get("NEXT_OF_KIN")).
                    //set("NEXT_OF_KIN_ADDR", m.get("NEXT_OF_KIN_ADDR")).
                    //set("NEXT_OF_KIN_PHONE", m.get("NEXT_OF_KIN_PHONE")).
                    //set("SEND_STATUS",(Integer) m.get("SEND_STATUS"))
                    .save();
        } catch (Exception ex) {
            String flagOra = getOraCode(ex);
//主键冲突
            if (flagOra.equals("00001")) {
                flag = true;

                Iterator i = m.entrySet().iterator();
                while (i.hasNext()) {//只遍历一次,速度快
                    Map.Entry e = (Map.Entry) i.next();
                    System.out.println(e.getKey() + "=" + e.getValue());

                }
                System.out.print("--------------------");
            } else {
                throw ex;
            }
        }

        //flag = new Test().set("aa", "bbbbbc").save();
        //  flag = new Clinic_appoints().set((String)e.getKey(), e.getValue()).save();
        return flag;
    }

    /**
     * 修改处理
     */
    public void toUpdate() {
        System.out.println("toUpdate start");
        String id = this.getPara("id");
        String movieid = this.getPara("movieid");
        String name = this.getPara("name");
        String description = this.getPara("description");
        String actor = this.getPara("actor");
        String path = this.getPara("path");

        boolean flag = MovieInfo.movieDao.findById(id).set("name", name)
                .set("movieid", movieid).set("description", description)
                .set("actor", actor).set("path", path).update();
        this.setAttr("flag", flag);
        if (flag) {
            toQuery();
        }
        System.out.println("toUpdate end");
    }

    public void toSearchDetail() {
        System.out.println("---toSearchDetail start---");
        MovieInfo movie = MovieInfo.movieDao.findById(this.getPara("id"));
        this.setAttr("movieInfo", movie);
        renderJsp("/jsp/toSearchDetail.jsp");
        System.out.println("---toSearchDetail end---");
    }

    /**
     * 删除处理
     */
    public void toDelete() {
        System.out.println("toDelete start");
        boolean flag = MovieInfo.movieDao.deleteById(this.getPara("id"));
        this.setAttr("flag", flag);
        if (flag) {
            toQuery();
        }
        System.out.println("---toDelete end---");
    }

    /**
     * 模板文件导入
     */
    public void toImport() {
        System.out.println("toImport");
    }

    // 自定义比较器：按书的价格排序  
    static class PriceComparator implements Comparator {

        @Override
        public int compare(Object object1, Object object2) {// 实现接口中的方法  
            Map p1 = (Map) object1; // 强制转换  
            Map p2 = (Map) object2;

            //首先比较年龄，如果年龄相同，则比较名字  
            int flag = ((String) (p1).get("CLINIC_LABEL")).compareTo((String) (p2).get("CLINIC_LABEL"));
            if (flag == 0) {
                return ((Date) (p1).get("APPT_MADE_DATE")).compareTo((Date) (p2).get("APPT_MADE_DATE"));
            } else {
                return flag;
            }
        }

    }

    public static java.sql.Timestamp getTimestamp(Date date) {
        return new java.sql.Timestamp(date.getTime());
    }

    public static String getOraCode(Exception e) {
        if (e == null) {
            return "";
        }
        String tmp = e.getMessage();
        int index = tmp.toUpperCase().indexOf("ORA-");
        if (index != -1) {
            return tmp.substring(index + 4, index + 9);
        }
        return "";
    }

    public Object deepClone(Object src) {
        Object o = null;
        try {
            if (src != null) {
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                ObjectOutputStream oos = new ObjectOutputStream(baos);
                oos.writeObject(src);
                oos.close();
                ByteArrayInputStream bais = new ByteArrayInputStream(
                        baos.toByteArray());
                ObjectInputStream ois = new ObjectInputStream(bais);
                o = ois.readObject();
                ois.close();
            }
        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
        }
        return o;
    }

}
